using System;
using System.Reflection;
using System.Text;
using Word = Microsoft.Office.Interop.Word;

namespace Glpt.Office
{
    /// <summary>
    /// 读取Word类
    /// </summary>
    public class ImportWord
    {
        /// <summary>
        /// 获取Word文档内容
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>文档内容</returns>
        public static string GetWordContent(string filename)
        {
            Word.Application wordApp = new Word.Application();
            Word.Document wordDoc = null;
            Object Nothing = Missing.Value;
            try
            {
                wordApp.Visible = false;
                Object path = filename as Object;
                wordDoc = wordApp.Documents.Open(ref path, false); //打开之前生成的文件
                int count = wordDoc.Paragraphs.Count;
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i <= count; i++)
                {
                    sb.Append(wordDoc.Paragraphs[i].Range.Text);
                }
                return sb.ToString();
            }
            finally
            {
                if (wordDoc != null)
                    wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                if (wordApp != null)
                    wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            }
        }
    }
}
